import React, {useEffect, useState} from 'react'
import {Space, Button, Popconfirm, message} from 'antd'
import moment from 'moment'
import {history} from 'umi'
import {
	PlusOutlined,
	ArrowDownOutlined,
	ArrowUpOutlined,
} from '@ant-design/icons'
import SearchForm from '@/components/SearchForm'
// import Table from '@/components/Table';
import {channelColumns, PageType} from '../constant'
import CustomTable from '@/components/Table'
import Styles from './index.less'

import {
	getChannelinnovationrewardsList,
	getFirstChannelType,
	removeSubmitFlow,
	updateStatus,
} from '@/service/merchantCenter/channelRule'
import {getAllCitys, getCompany} from '@/service/common'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {translateDataToTree} from '@/utils/common'
import {downloadDocumentUrl} from '@/service/common/download'
import ExportExcl from './impoart'
import Permissions from '@/components/Permissions'

export default function List({user}: any) {
	// const [dataList, setDataList] = useState<any[]>([{ id: '33' }]);
	const [tableList, setTableList] = useState<any[]>([])
	const [citysList, setCitysList] = useState<any[]>([])
	const [subjectList, setSubjectList] = useState([])
	const [orgList, setOrgList] = useState([])
	const [importExcl, setImportExcl] = useState(false) // 导入弹框
	const [channelTypeOneType, setChannelTypeOneType] = useState([])
	const [searchData, setSearchData] = useState({})
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	/** 获取所属公司数据 */
	const onCompany = () => {
		// eslint-disable-next-line react/destructuring-assignment
		getCompany({merchantId: user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				// setCompanyData(list as any);
				setOrgList(list)
			}
		})
	}
	const getChannelTypeOneType = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.data?.length) {
				setChannelTypeOneType(res.data)
			}
		})
	}

	const formItems = [
		{
			type: 'group',
			key: 'group',
			groupItems: [
				{
					type: 'input',
					label: '编码',
					name: 'channelNo',
					key: 'channelNo',
					placeholder: '请输入',
				},
				{
					type: 'input',
					label: '名称',
					name: 'name',
					key: 'name',
					placeholder: '请输入',
				},
				{
					type: 'select',
					label: 'AMC一级渠道类型',
					name: 'channelTypeOne',
					key: 'channelTypeOne',
					title: 'text',
					items: channelTypeOneType.map((item: any) => ({
						value: item.type,
						text: item.valueName,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					label: 'AMC二级渠道类型',
					name: 'channelTypeTwo',
					key: 'channelTypeTwo',
					placeholder: '请选择',
					title: 'text',
					items: [
						{id: '1', name: '渠道sp'},
						{id: '2', name: '车司'},
						{id: '3', name: '自营-BD'},
						{id: '4', name: '自营-司推司'},
						{id: '5', name: '自营-普推司'},
					].map((item: any) => ({
						value: item.id,
						text: item.name,
					})),
				},
				{
					type: 'select',
					label: ' 状态',
					name: 'status',
					key: 'status',
					title: 'text',
					placeholder: '请选择',
					items: [
						{value: '0', name: '待审核'},
						{value: '1', name: '审核通过'},
						{value: '2', name: '审核失败'},
						{value: '3', name: '审核中'},
						{value: '4', name: '已作废'},
					].map((item: any) => ({
						value: item.value,
						text: item.name,
					})),
				},
				{
					type: 'select',
					label: '是否有效',
					name: 'isValid',
					key: 'isValid',
					title: 'text',
					placeholder: '请选择',
					items: [
						{value: '0', name: '无效'},
						{value: '1', name: '有效'},
					].map((item: any) => ({
						value: item.value,
						text: item.name,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					label: '所属主体',
					name: 'subject',
					key: 'subject',
					title: 'text',
					items: subjectList.map((item: any) => ({
						value: item.id,
						text: item.merchantName,
					})),
				},
				{
					type: 'treeSelect',
					label: '所属公司',
					name: 'orgId',
					key: 'orgId',
					keys: 'id',
					title: 'name',
					treeData: [...orgList],
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					placeholder: '请选择',
					items: citysList,
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'timeRange',
					label: '创建时间 ',
					name: 'date',
					key: 'date',
					placeholder: '请输入',
				},
				{
					type: 'input',
					label: ' 创建人',
					name: 'createName',
					key: 'createName',
					placeholder: '请输入',
				},
				{},
			],
		},
	]

	const openDetail = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/channelRule/detail',
			query: {
				pageType: PageType.Detail,
				id: record.id,
				examine: record.examine,
				processInstanceId: record.instanceId,
				orgId:record.orgId,
				processId:record.instanceId,
			},
		})
	}

	const openAudit = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/channelRule/detail',
			query: {
				pageType: 'audit',
				id: record.id,
				examine: record.examine.toString(),
				processInstanceId: record.instanceId,
				orgId:record.orgId,
				processId:record.instanceId,
			},
		})
	}

	const openEditPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/channelRule/edit',
			query: {
				pageType: PageType.Edit,
				id: record.id,
			},
		})
	}

	const getTabelValue = async () => {
		setLoading(true)
		const res = await getChannelinnovationrewardsList({
			...params,
			...searchData,
		})
		if (res?.data) {
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				setTableList(res.data?.records || [])
			}
		}
		setLoading(false)
	}

	const onFinish = (values: any) => {
		const newValues = {...values}
		if (values?.date) {
			newValues.startDate = moment(newValues.date[0]).format('YYYY-MM-DD')
			newValues.endDate = moment(newValues.date[1]).format('YYYY-MM-DD')
		}
		delete newValues.date
		setSearchData(values)
		setParams({
			current: 1,
			size: 10,
		})
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data || [])
			}
		})
	}

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		getSubjectFun()
		onCompany()
		getChannelTypeOneType()
	}, [])

	useEffect(() => {
		getTabelValue()
	}, [params])

	const Colunms: any[] = [
		...channelColumns,
		{
			title: '操作',
			width: 350,
			align: 'center',
			fixed: 'right',
			render: (ffield: string, record: any) => {
				if (record.status === 0) {
					return (
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channelRule_detail">
								<Button
									type="link"
									onClick={() => openDetail(record)}>
									详情
								</Button>
							</Permissions>
							{record.commodityType === 2 && (
								<>
									<Permissions permissionID="amc_merchantCenter_channelRule_edit">
										<Button
											type="link"
											onClick={() =>
												openEditPage(record)
											}>
											编辑
										</Button>
									</Permissions>
									<Permissions permissionID="amc_merchantCenter_channelRule_del">
										<Popconfirm
											placement="topLeft"
											title="你确定要删除这条渠道拉新规则吗？"
											onConfirm={async () => {
												const res =
													await removeSubmitFlow({
														ids: record.id,
													})
												if (res.success) {
													message.success('删除成功')
													getTabelValue()
												}
											}}
											okText="确定"
											cancelText="取消">
											<Button type="link">删除</Button>
										</Popconfirm>
									</Permissions>
									{record.examine &&
										record.commodityType === 2 && (
											<Permissions permissionID="amc_merchantCenter_channelRule_audit">
												<Button
													type="link"
													onClick={() =>
														openAudit(record)
													}>
													审核
												</Button>
											</Permissions>
										)}
								</>
							)}
						</Space>
					)
				}
				if (record.status === 3) {
					return (
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channelRule_detail">
								<Button
									type="link"
									onClick={() => openDetail(record)}>
									详情
								</Button>
							</Permissions>
							{record.examine && (
								<Permissions permissionID="amc_merchantCenter_channelRule_audit">
									<Button
										type="link"
										onClick={() => openAudit(record)}>
										审核
									</Button>
								</Permissions>
							)}
						</Space>
					)
				}

				if (record.status === 4) {
					return (
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channelRule_detail">
								<Button
									type="link"
									onClick={() => openDetail(record)}>
									详情
								</Button>
							</Permissions>
							{record.commodityType === 2 && (
								<>
									<Permissions permissionID="amc_merchantCenter_channelRule_edit">
										<Button
											type="link"
											onClick={() =>
												openEditPage(record)
											}>
											再次发起
										</Button>
									</Permissions>
									<Popconfirm
										placement="topLeft"
										title="你确定要删除这条渠道拉新规则吗？"
										onConfirm={async () => {
											const res = await removeSubmitFlow({
												ids: record.id,
											})
											if (res.success) {
												message.success('删除成功')
												getTabelValue()
											}
										}}
										okText="确定"
										cancelText="取消">
										<Permissions permissionID="amc_merchantCenter_channelRule_del">
											<Button type="link">删除</Button>
										</Permissions>
									</Popconfirm>
								</>
							)}
						</Space>
					)
				}
				if (record.status === 1) {
					return (
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channelRule_detail">
								<Button
									type="link"
									onClick={() => openDetail(record)}>
									详情
								</Button>
							</Permissions>
							{record.commodityType === 2 &&
								moment(record?.endDate).add(+1, 'day') >
									moment() && (
									<>
										{record.isValid === 1 && (
											<Permissions permissionID="amc_merchantCenter_channelRule_operation">
												<Button
													type="link"
													onClick={async () => {
														const res =
															await updateStatus({
																type: 0,
																id: record.id,
															})
														if (res.success) {
															message.success(
																'操作成功',
															)
															getTabelValue()
														}
													}}>
													终止
												</Button>
											</Permissions>
										)}
										{record.isValid === 0 && (
											<Permissions permissionID="amc_merchantCenter_channelRule_operation">
												<Button
													type="link"
													onClick={async () => {
														const res =
															await updateStatus({
																type: 1,
																id: record.id,
															})
														if (res.success) {
															message.success(
																'操作成功',
															)
															getTabelValue()
														}
													}}>
													启动
												</Button>
											</Permissions>
										)}
									</>
								)}
						</Space>
					)
				}
				return ''
			},
		},
	]
	const sunChange = (value: any) => {
		if (value) {
			setImportExcl(false)
			getTabelValue()
		}
	}

	return (
		<div className={Styles.list}>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '150px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={formItems}
					onFinish={onFinish}
					onReset={onReset}
				/>
			</div>
			<div className={Styles.content}>
				<div className={Styles.btnListBox}>
					<div>
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channelRule_add">
								<Button
									onClick={() => {
										history.push(
											'/merchantCenter/channelRule/add',
										)
									}}
									icon={<PlusOutlined />}
									type="primary"
									ghost
									size="small">
									新增
								</Button>
							</Permissions>

							<Permissions permissionID="amc_merchantCenter_channelRule_import">
								<Button
									icon={<ArrowUpOutlined />}
									className={Styles.warning}
									ghost
									size="small"
									onClick={() => {
										setImportExcl(true)
									}}>
									导入
								</Button>
							</Permissions>

							<Permissions permissionID="amc_merchantCenter_channelRule_export">
								<Button
									icon={<ArrowDownOutlined />}
									className={Styles.import}
									ghost
									size="small"
									onClick={() => {
										downloadDocumentUrl({
											resourceId: '173',
											queryDesc:
												'渠道拉新奖励规则列表导出,resourceId:173',
											queryParam: searchData,
										})
									}}>
									导出
								</Button>
							</Permissions>
						</Space>
					</div>
				</div>
				<CustomTable
					params={params}
					columns={Colunms}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
			</div>
			<ExportExcl info={importExcl} sunchange={sunChange} />
		</div>
	)
}
